package org.example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class StreamWordCount {
    public static void main(String... args){

        //1. 初始化流环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        List<String> list = new ArrayList<>();
        list.add("hello world!");
        list.add("hello java");
        list.add("hello flink");
        //2. 获取数据
        DataStreamSource<String> source = env.fromCollection(list);

        //3. 数据转换
        SingleOutputStreamOperator<Tuple2<String,Long>> operator = source.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for(String word : words){
                    collector.collect(Tuple2.of(word,1L));
                }
            }
        }).returns(Types.TUPLE(Types.STRING,Types.LONG));

        //数据分组
        KeyedStream<Tuple2<String,Long>, String> keyedStream =  operator.keyBy(data -> data.f0);
        //求和
        SingleOutputStreamOperator<Tuple2<String,Long>> sums = keyedStream.sum(1);
        //打印
        sums.print();
        //执行，提交任务
        try {
            env.execute();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
